//
//  func_point.cpp
//  learnC++
//
//  Created by apple on 2018/6/1.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#include "func_point.hpp"

int foo(int value,int ok = 10) // code starts at memory address 0x002717f0
{
    return value+ok;
}

int goo(int value)
{
    return value;
}
//升序
bool ascending(int x, int y)
{
    return x > y; // swap if the first element is greater than the second
}
//降序
bool descending(int x, int y)
{
    return x < y; // swap if the second element is greater than the first
}

//奇偶排列
bool evensFirst(int x, int y)
{
    // if x is even and y is odd, x goes first (no swap needed)
    if ((x % 2 == 0) && !(y % 2 == 0))
        return false;
    
    // if x is odd and y is even, y goes first (swap needed)
    if (!(x % 2 == 0) && (y % 2 == 0))
        return true;
    
    // otherwise sort in ascending order
    return ascending(x, y);
}

void printArray(int *array, int size)
{
    for (int index=0; index < size; ++index)
        std::cout << array[index] << " ";
    std::cout << '\n';
}

void select(compare compare = ascending){
    
}

void select2(validateFunc func = ascending){
    
}
//C++  11
void select3(int x,int y,std::function<bool(int,int)> func){
    std::function<int(int)> ptr = goo;
}

//求数组最小值
void SelectionSort(int *array, int size, bool (*compare)(int,int) = ascending)
{
    for (int startIndex = 0; startIndex < size; ++startIndex)
    {
        int index = startIndex;
        
        for (int currentIndex = startIndex + 1; currentIndex < size; ++currentIndex)
        {
            //函数指针调用
            if (compare(array[index],array[currentIndex])) {
                index = currentIndex;
            }
        }
        
        std::swap(array[startIndex], array[index]);
    }
}

//function pointer函数指针
void test_function_point(){
//    std::cout << reinterpret_cast<void*>(foo);
    
    int (*funPtr)(int,int) = foo;
    
    
    //使用函数指针调用(2种调用方法)
    funPtr(5,6);//隐式调用
    (*funPtr)(6,5);//显式调用
    //NOTE:函数指针在运行时被解析,缺省参数在编译时被解析,在这种情况下，您将明确地必须传入任何默认参数的值
    
    
    std::cout << (*funPtr)(7,8) << "\n";
    
    
    //函数指针但参数传递
    int array[9] = { 3, 7, 9, 5, 6, 1, 8, 2, 4 };
    //ascending = &ascending
    SelectionSort(array, sizeof(array)/sizeof(array[0]), ascending);
    printArray(array, sizeof(array)/sizeof(array[0]));

    SelectionSort(array, sizeof(array)/sizeof(array[0]), descending);
    printArray(array, sizeof(array)/sizeof(array[0]));
                          
}
